"use strict";

//=============
// 引入程序依赖
//=============
import React, { Component } from 'react' ;
import { connect } from 'react-redux' ;
import NetworkEngine from '../../../utils/NetworkEngine' ;
import UrlManager from '../../../utils/UrlManager' ;
import { mapStateToProps, mapDispatchToProps } from './CampaignDetailRedux';
//images

import xiala from "../../../static/img/h5/xiala.png";
import address from "../../../static/img/h5/address.jpg";
import datetime from "../../../static/img/h5/datetime.jpg";
import enroll from "../../../static/img/h5/enroll.jpg";
import share from "../../../static/img/h5/share.jpg";
import shareModal from "../../../static/img/h5/shareModal.png";
import './CampaignDetail.scss'

var weixinUrl = location.href.split('#')[0];

class CampaignDetailContainer extends Component{
    constructor(props){
        super(props) ;
        this.state={
            detail:null,
            isWeixn:1
        }
    }

    componentWillMount() {
        this.isWeixn();
        this.list();
        this.great();
    }

    componentDidMount() {
        let id = sessionStorage.getItem('id');
        if (id == null) {
            $(this.refs.height).css("bottom","1.35rem");
        } else {
            $(this.refs.height).css("bottom","0");
            $(this.refs.height).css("overflow-y","visible");
        }
    }

    //初始化首页信息
    initialCampaignDetail() {
        let urlManager = new UrlManager();
        NetworkEngine(
            "get",
            urlManager.campaignDetail() + `/${this.props.params.id}`,
        ).then(
            data => {

                let detail = data.data.data;
                this.setState({
                    detail:detail
                })
            }
        ).catch(
            err => {
            }
        )
    }

    great(){
        this.initialCampaignDetail();
    }
    //还原HTML脚本语言
    unescapeHTML(description) {
        let html = description.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
        //需求详细
        return {__html:html};
    }

    isWeixn(){
        let ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            this.setState({
                isWeixn:1
            })
        } else {
            this.setState({
                isWeixn:0
            })
        }
    }

    parserDate(date) {
        return new Date(Date.parse(date.replace(/-/g, "/")));
    }
    dateCheck(time){
        let date = this.parserDate(time);
        let nowDate = new Date();
        if(date.getTime() > nowDate.getTime()){
            return 1;
        } else {
            return 0;
        }
    }

    fromatDate(time,flg,timeFlg) {
        if (!time) {
            return time;
        }
        let date = this.parserDate(time);

        let week = {
            "0" : "周日",
            "1" : "周一",
            "2" : "周二",
            "3" : "周三",
            "4" : "周四",
            "5" : "周五",
            "6" : "周六"
        };
        let arr = time.split(" ");
        let dateStr = "";
        let timeStr = "";
        if (arr.length > 1) {
            dateStr = arr[0];
            timeStr = arr[1];
            let dateArr = dateStr.split("-");
            if (dateArr.length > 2) {
                if (timeFlg == 1) {
                    return timeStr;
                } else if (flg == 1) {
                    return dateArr[1]+"月"+dateArr[2]+"日"+" "+week[date.getDay()]+timeStr;
                } else {
                    return dateArr[0]+"年"+dateArr[1]+"月"+dateArr[2]+"日"+" "+week[date.getDay()]+timeStr;
                }
            }
        }
        return time;
    }
    timeShow(time1,time2){
        let nowDate = new Date();
        let flg = 0;
        let timeFlg = 0;
        let arr1 = time1.split("-");
        let arr2 = time2.split("-");

        if (arr1[0] == arr2[0]) {
            if(arr1[0] == nowDate.getFullYear()) {
                flg = 1;
            }
        }
        let t1 = this.fromatDate(time1,flg,timeFlg);
        let date1 = time1.split(" ")[0];
        let date2 = time2.split(" ")[0];

        if (date1 == date2) {
            timeFlg = 1;
        }
        let t2 = this.fromatDate(time2,flg,timeFlg);
        return t1+" - "+t2;
    }
    showModal() {
        $(this.refs.shareBgm).show();
    }
    cancelModal() {
        $(this.refs.shareBgm).hide();
    }

    list() {
        var url = window.location.href;
        if (url.indexOf("?") > -1) {
            window.location.href = url.split("?")[0];
            return;
        }
        weixinUrl = weixinUrl.replace(/\//g, '_');
        let urlManager = new UrlManager();
        NetworkEngine(
            "get",
            urlManager.shareWeiXinCampaign() + "/" + weixinUrl,
        ).then(
            data => {
                this.shareSuccess(data.data)
            }
        ).catch(
            err => {
            }
        )
    }

    shareSuccess(data) {
        // let _this = this;
        // let title = _this.state.title;
        // let videoImgUrl = _this.state.videoImgUrl;
        // let des = _this.state.introduction;
        // let videoUrl = window.location.href;
        /*---------------微信分享------------------*/
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: 'wxae5b39ca398c9f2f', // 必填，公众号的唯一标识
            // appId: 'wx4002b019d6429df6', // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名，见附录1
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function () {
            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
            // console.log("title:" + _this.state.title);
            // console.log("VideoUrl:" + videoUrl);
            // console.log("videoImgUrl:" + videoImgUrl);

            // let that = _this;
            wx.onMenuShareTimeline({
                title: data.title, // 分享标题
                link: data.videoUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                //imgUrl: localStorage.getItem("videoImg"), // 分享图标
                imgUrl: data.videoImgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            wx.onMenuShareAppMessage({
                title: data.title, // 分享标题
                desc: data.des, // 分享描述
                link: data.videoUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: data.videoImgUrl, // 分享图标
                type: 'link', // 分享类型,music、video或link，不填默认为link
                dataUrl: data.videoUrl, // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        });
        wx.error(function (res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });
    }
    render(){
        if(!this.state.detail){
            return(
                <div></div>
            )
        } else {
            let dateCheckFlg = this.dateCheck(this.state.detail.endTime);
            return (
                <div>
                    <div className="weixn-share-img"><img src={this.state.detail.imgUrl} alt=""/></div>
                    <div ref="shareBgm" onClick={this.cancelModal.bind(this)} className="share-bgm" style={{display:"none"}}>
                        <img src={shareModal} alt=""/>
                    </div>
                    <div className="h5-wrapper" ref="height">
                        <table className="h5-head-activity">
                            <tbody>
                            <tr>
                                <td>活动</td>
                            </tr>
                            </tbody>
                        </table>
                        <div className="activties-content">
                            <div className="banner"><img src={this.state.detail.imgUrl} alt=""/></div>
                            <div className="activties-content-1">
                                <div className="title">
                                    {this.state.detail.title}
                                </div>
                                <div className="activties-content-time">
                                    <div><img src={datetime} alt=""/></div>
                                    <div><span>{this.timeShow(this.state.detail.startTime,this.state.detail.endTime)}</span></div>
                                    <div className="clear"></div>
                                </div>
                                <div className="activties-content-site">
                                    <div><img src={address} alt=""/></div>
                                    <div><span>{this.state.detail.location}</span></div>
                                    <div className="clear"></div>
                                </div>
                            </div>
                            <div className="line-"></div>
                            <div className="activties-cont">
                                <div>活动简介</div>
                                <div>{this.state.detail.introduction}</div>
                                <div>活动详情</div>
                                <div dangerouslySetInnerHTML={this.unescapeHTML(this.state.detail.details)}></div>
                            </div>
                            {
                                this.state.isWeixn == 1 ?
                                    <div className="activties-footer weixn">
                                        {
                                            dateCheckFlg==1 && this.state.detail.status==0 ?
                                                <div className="time-right">
                                                    <a href={this.state.detail.address} target="_blank">
                                                        <img src={enroll} alt=""/>
                                                        <span>报名</span>
                                                    </a>
                                                </div>
                                                :
                                                <div className="time-over">
                                                    <span>活动已结束</span>
                                                </div>
                                        }
                                        <div className="share-button" onClick={this.showModal.bind(this)}>
                                            <img src={share} alt=""/>
                                            <span>分享</span>
                                        </div>
                                        <div className="clear"></div>
                                    </div>
                                    :
                                    <div className="activties-footer weixn-other">
                                        {
                                            dateCheckFlg==1 && this.state.detail.status==0 ?
                                                <div className="time-right">
                                                    <a href={this.state.detail.address} target="_blank">
                                                        <img src={enroll} alt=""/>
                                                        <span>报名</span>
                                                    </a>
                                                </div>
                                                :
                                                <div className="time-over">
                                                    <span>活动已结束</span>
                                                </div>
                                        }
                                        <div className="clear"></div>
                                    </div>
                            }
                        </div>
                    </div>
                </div>
            )
        }
    }
}

const CampaignDetail = connect(mapStateToProps, mapDispatchToProps)(CampaignDetailContainer) ;

export { CampaignDetail as default } ;
